package org.je.xml;

import java.util.ArrayList;
import java.util.List;

import org.je.ufo.Int;
import org.je.util.StringUtil;

/**
 * @author fanyifeng
 */
public class XUtil
{
	/**
	 * @param xml
	 */
	public static Element parse(String xml) {
		if (xml == null) //
			return null;
		Int offset = new Int();
		XmlEleUtil.tryFindXmlHead(xml ,offset);
		List<Element> list = new ArrayList<Element>();

		while( true ) {
			Element ele = XmlGramUtil.nextElement(xml ,offset);
			if (ele == null) //
				break;
			if (! (ele.type == Element.XML_TEXT && StringUtil.isBlank(ele.value))) //
				list.add(ele);
		}

		for (int i = 0; i < list.size(); ++i) {
			Element ele = list.get(i);
			if (ele.type == Element.XML_NOTES) //
				continue;
			if (ele.type == Element.XML_CLOSED_NODE) //
				return ele;
			if (ele.type == Element.TAG_START) {
				XmlGramUtil.matchEndTag(ele ,list ,i + 1 ,xml);
				return ele;
			}
			throw new ParseXmlException(XmlGramUtil.error(xml ,"illegal start tag" ,ele.offset));
		}
		throw new ParseXmlException("cant-find-element");
	}

}
